package com.ebt.m.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.ebt.m.R;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.config.DataBaseUpdateConfig;
import com.ebt.m.data.DataBaseUpdate;
import com.ebt.m.data.DatabaseManager;
import com.ebt.m.exception.EBTException.EBTException;
import com.ebt.m.utils.fileutils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class EBTInit {

    /**
     * 初始化
     *
     * @param context
     */
    synchronized public static void init(Context context) {
        try {
            // 检测数据库目录是否存在不存在就创建
            File databaseDir = new File(ConfigData.DATABASE_PATH);
            // 需要先检测目标文件夹下的文件是否存在
            if (!EbtUtils.checkDb()) {// 目录或者文件不存在
                InputStream input = context.getResources().openRawResource(R.raw.ebt);// 获得raw中的数据文件
                FileUtils.copyFile(input, ConfigData.DATABASE);
                DatabaseManager dm = DatabaseManager.getInstance(context);
                dm.close();
            }
            EbtUtils.checkRepository();
            File imgDirPhoto = new File(ConfigData.PHOTO_PATH);
            if (!imgDirPhoto.exists()) {
                imgDirPhoto.mkdirs();
            }
            File imgDir1 = new File(ConfigData.PORTRAITPATH);
            if (!imgDir1.exists()) {
                imgDir1.mkdirs();
            }
            if (!checkPHOTO(ConfigData.PHOTO_SELETED)) {
                System.out.println(ConfigData.PHOTO_DEFAULT_FILE);
            }
            // 初始化数据库版本更新操作
            DataBaseUpdateConfig.init(context);
            DataBaseUpdate databaseUdate = new DataBaseUpdate(context);
            databaseUdate.updateEbtDataBase();
            // 如果存在apk删除
            File apkPath = new File(ConfigData.UPDATE_APK_FILE_PATH);
            if (apkPath != null && apkPath.exists()) {
                apkPath.delete();
            }
            initAssets(context);
        } catch (EBTException e) {
            Logger.e(e);
        }
    }

    private static void initAssets(Context context) {
        String path = ConfigData.DATA_PATH + File.separator + "wikibrand";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

        CommonUtil.copyAssetsToSD(context, "theme.css", ConfigData.PATH_RESOURCES + "theme.css");
        CommonUtil.copyAssetsToSD(context, "autoexplain.css", ConfigData.PATH_RESOURCES + "autoexplain.css");
        CommonUtil.copyAssetsToSD(context, "autoexplain.js", ConfigData.PATH_RESOURCES + "autoexplain.js");
        CommonUtil.copyAssetsToSD(context, "proposal.png", ConfigData.PORTRAITPATH + File.separator + "proposal.png");
        CommonUtil.copyAssetsToSD(context, "card.png", ConfigData.PORTRAITPATH + File.separator + "card.png");
        CommonUtil.copyAssetsToSD(context, "logo.png", ConfigData.PORTRAITPATH + File.separator + "logo.png");
        CommonUtil.copyAssetsToSD(context, "icon_none.png", ConfigData.PORTRAITPATH + File.separator + "icon_none.png");

        File noMedia = new File(ConfigData.PORTRAITPATH, ".nomedia");
        if (!noMedia.exists()) {
            try {
                noMedia.createNewFile();
            } catch (IOException e) {
            }
        }
    }

    public static void copyDB(Context context) {
        // 检测数据库目录是否存在不存在就创建
        File databaseDir = new File(ConfigData.DATABASE_PATH);
        InputStream input = context.getResources().openRawResource(R.raw.ebt);// 获得raw中的数据文件
        // 需要先检测目标文件夹下的文件是否存在
        if (!EbtUtils.checkDb()) {// 目录或者文件不存在
            Log.d("EBTInit-无ebt数据库文件，首次拷贝", databaseDir.getAbsolutePath());
            FileUtils.copyFile(input, ConfigData.DATABASE);
        }
    }

    @Deprecated
    public static void deleteDb() {
        String path = ConfigData.DATABASE;
        File f = new File(path);
        if (f.exists() && f.isFile()) {// 文件存在
            // 备份一份
            f.delete();
        }

    }

    public static void doCopyDefaultePhoto(InputStream input) {

        // Log.d("首次使用 初始化相片", "首次使用 初始化相片");

        OutputStream output = null;
        try {
            output = new FileOutputStream(ConfigData.PHOTO_SELETED);
            byte[] buffer = new byte[2048];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (null != output) {
                    output.flush();
                    output.close();
                }
                if (null != input) {
                    input.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /***
     * 检测桌面相册是否存在
     *
     * @param path
     * @return
     */
    public static boolean checkFileExists(String path) {
        File file = new File(path);

        if (!file.exists() || !file.canRead() || !file.isFile()) {
            return false;
        }
        return true;
    }

    /***
     * 检测桌面相册是否存在
     *
     * @param path
     * @return
     */
    public static boolean checkPHOTO(String path) {
        File file = new File(path);

        if (!file.exists() || !file.canRead() || !file.isFile()) {
            return false;
        }
        return true;
    }

    public static void addPhoto(InputStream bos, String path) {
        // TODO Auto-generated method stub
        OutputStream output = null;
        try {
            output = new FileOutputStream(path);
            byte[] buffer = new byte[2048];
            int length;
            while ((length = bos.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (null != output) {
                    output.flush();
                    output.close();
                }
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void initImagePath(Context context, String dirPath, String imageFilePath, int drawableResID) {
        try {
            File fileDir = new File(dirPath);
            if (!fileDir.exists()) {
                try {
                    fileDir.mkdirs();
                } catch (Exception e) {
                }
            }

            File file = new File(imageFilePath);
            if (!file.exists()) {
                file.createNewFile();
                Bitmap pic = BitmapFactory.decodeResource(context.getResources(), drawableResID);
                FileOutputStream fos = new FileOutputStream(file);
                pic.compress(CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

}
